package com.example.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

@Component
@Aspect
public class TransactionalAop {

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Around(value = "@annotation(com.example.common.annotation.MyTransactional)")
    public Object around(ProceedingJoinPoint point){
        TransactionStatus transaction = null;
        try {
            System.out.println(">>>>开始aop");
            transaction = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
            Object proceed = point.proceed();
            System.out.println(">>>>结束aop");
            dataSourceTransactionManager.commit(transaction);
            return proceed;
        } catch (Throwable throwable) {
            System.out.println(">>>>错误!!");
            if (transaction != null) {
                dataSourceTransactionManager.rollback(transaction);
            }
            throwable.printStackTrace();
            return "系统错误!";
        }

    }
}
